<template>
  <div class="role-container">
    <div class="app-container calendar-list-container">
      <el-form>
        <el-row class="row-bg" justify="space-around" type="flex">
          <el-col :span="12">
            <el-form-item label="客户端类型">
              <el-select
                @change="queryAllPermitList"
                v-model="queryCondition.clientType"
              >
                <el-option
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  v-for="item in clientType"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" />
        </el-row>
        <el-row :gutter="0" class="cutOffLine">
          <div class="buttonGroup">
            <el-button @click="queryAllPermitList" size="small" type="primary">
              <icon name="search" />
              查询
            </el-button>
          </div>
        </el-row>
      </el-form>
    </div>
    <el-table
      :data="permitTree"
      :show-header="false"
      :tree-props="{ children: 'subMenu' }"
      fit
      ref="menuTreeRef"
      row-key="id"
      default-expand-all
    >
      <el-table-column width="1px" />
      <el-table-column width="50px" align="center" property="showOrder">
        <template slot-scope="scope">
          <el-input
            placeholder="序号"
            v-if="scope.row.isEdit"
            v-model="modifyPermitInfo.showOrder"
          />
          <span style="vertical-align: middle" v-else>{{
            scope.row.showOrder
          }}</span>
        </template>
      </el-table-column>
      <el-table-column width="20px">
        <template slot-scope="scope">
          <icon v-if="scope.row.isEdit" :name="modifyPermitInfo.icon"></icon>
          <icon v-else :name="scope.row.icon" style="vertical-align: middle" />
        </template>
      </el-table-column>
      <el-table-column property="showName" width="200px">
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEdit"
            placeholder="名称"
            v-model="modifyPermitInfo.showName"
          />
          <div v-else>
            {{ scope.row.showName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column width="150px">
        <template slot-scope="scope">
          <el-select
            v-if="scope.row.isEdit"
            v-model="modifyPermitInfo.permitType"
          >
            <el-option
              :key="item.value"
              :label="item.label"
              :value="item.value"
              v-for="item in getMenuType()"
            >
            </el-option>
          </el-select>
          <span v-else>{{
            scope.row.permitType | displayLabelValue(getMenuType())
          }}</span>
        </template>
      </el-table-column>
      <el-table-column property="url" width="300px">
        <template slot-scope="scope">
          <el-input
            placeholder="目标地址"
            v-if="scope.row.isEdit"
            v-model="modifyPermitInfo.url"
          />
          <span v-else>{{ scope.row.url }}</span>
        </template>
      </el-table-column>
      <el-table-column property="status" width="80px">
        <template slot-scope="scope">
          <!-- <el-input
                        placeholder="是否显示"
                        v-if="scope.row.isEdit"
                        v-model="modifyPermitInfo.status"
                    /> -->
          <el-select
            v-model="modifyPermitInfo.status"
            v-if="scope.row.isEdit"
            placeholder="是否显示"
          >
            <el-option
              v-for="item in isShowList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <span v-else>{{ scope.row.status === "1" ? "是" : "否" }}</span>
        </template>
      </el-table-column>
      <el-table-column property="key" width="150px">
        <template slot-scope="scope">
          <el-input
            placeholder="key"
            v-if="scope.row.isEdit"
            v-model="modifyPermitInfo.key"
          />
          <span v-else>{{ scope.row.key }}</span>
        </template>
      </el-table-column>
      <el-table-column width="100px">
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEdit"
            placeholder="icon"
            v-model="modifyPermitInfo.icon"
          >
          </el-input>
        </template>
      </el-table-column>
      <el-table-column width="200px">
        <template slot-scope="scope">
          <span class="custom-tree-node" v-if="scope.row.isEdit">
            <el-button @click="() => finish(scope.row)" size="mini" type="text">
              完成
            </el-button>
            <el-button
              @click="() => cancel(scope.row, scope.$index)"
              size="mini"
              type="text"
            >
              取消
            </el-button>
          </span>
          <span v-else>
            <el-button
              @click="() => add(scope.row)"
              size="mini"
              type="text"
              v-if="isAddMode == false && isEditMode == false"
            >
              添加
            </el-button>
            <el-button
              @click="() => modify(scope.row)"
              size="mini"
              type="text"
              v-if="
                isAddMode == false && isEditMode == false && scope.row.id !== 0
              "
            >
              修改
            </el-button>
            <el-button
              @click="() => deletePermit(scope.row)"
              size="mini"
              type="text"
              v-if="
                isAddMode == false && isEditMode == false && scope.row.id !== 0
              "
            >
              删除
            </el-button>
          </span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>

export default {
  data() {
    return {
      isShowList: [
        {
          label: '否',
          value: '0'
        },
        {
          label: '是',
          value: '1'
        }
      ],
      apiName: {
        queryAllPermitList: this.apiType.admin.queryAllPermitList,
        addPermit: this.apiType.admin.addPermit,
        modifyPermit: this.apiType.admin.modifyPermit,
        deletePermit: this.apiType.admin.deletePermit
      },
      queryCondition: {
        permitName: '',
        clientType: 'WEB'
      },
      permitTree: [{
        id: 0,
        showName: '菜单配置',
        permitType: '',
        disabled: true,
        subMenu: [],
        status: '1'
      }],
      isAddMode: false,
      isEditMode: false,
      initPermitInfo: {
        id: '',
        parentPermitId: '',
        permitType: '',
        parent: {},
        name: '',
        key: '',
        url: '',
        showName: '',
        showOrder: '',
        icon: 'cog',
        status: '',
        subMenu: '',
        isEdit: false
      },
      modifyPermitInfo: {},
      currentSelectPermitId: '',
      defaultPermitProps: {
        children: 'subMenu',
        label: 'showName'
      },
      currentPage: 1,
      pageSize: 20,
      totalCount: 0
    }
  },
  mounted() {
    this.queryAllPermitList()
  },
  watch: {
    currentSelectPermitId(val) {
      this.$refs.permitTree.setCheckedKeys([val])
      this.showRolePermitList(val)
    },
    permitTree() {
      this.$refs['menuTreeRef'].doLayout()()
    }
  },
  methods: {
    getMenuType() {
      if (this.queryCondition.clientType === 'PUBLIC') {
        return this.wechatPlatformMenuType
      } else {
        return this.menuType
      }
    },
    check(arg) {
      console.log('check', arg)
    },
    add(data) {
      console.log('add', data)
      this.modifyPermitInfo = this.initPermitInfo
      this.modifyPermitInfo.id = -1
      this.modifyPermitInfo.parentPermitId = data.id !== 0 ? data.id : null
      this.modifyPermitInfo.showName = '新建菜单'
      this.modifyPermitInfo.subMenu = ''
      this.modifyPermitInfo.permitType = 'MENU'
      this.modifyPermitInfo.isEdit = true
      if (!data.subMenu) {
        this.$set(data, 'subMenu', [])
      }
      data.subMenu.push(this.modifyPermitInfo)
      this.modifyPermitInfo.showOrder = data.subMenu.length
      console.log('after push', data)
      this.modifyPermitInfo.parent = JSON.parse(JSON.stringify(data))
      this.isAddMode = true
      console.log('finish push', this.modifyPermitInfo)
    },
    cancel(data) {
      this.$set(data, 'isEdit', false)
      if (this.isAddMode) {
        const parentInfo = this.findParent(-1, this.permitTree[0])
        parentInfo.subMenu.splice(parentInfo.index, 1)
      }
      this.isEditMode = false
      this.isAddMode = false
    },
    modify(data) {
      this.$set(data, 'isEdit', true)
      this.modifyPermitInfo = JSON.parse(JSON.stringify(data))
      this.isEditMode = true
    },
    finish(data) {
      this.$set(data, 'isEdit', false)
      this.$set(data, 'name', this.modifyPermitInfo.key)
      if (this.isEditMode) {
        this.modifyPermit(this.modifyPermitInfo)
        this.isEditMode = false
      }
      if (this.isAddMode) {
        this.addPermit(this.modifyPermitInfo)
        this.isAddMode = false
      }
      this.modifyPermitInfo = this.initPermitInfo
    },
    findParent(id, tree) {
      let parentInfo = { index: -1, subMenu: [] }
      if (Array.isArray(tree.subMenu)) {
        parentInfo.index = tree.subMenu.findIndex(d => d.id === id)
        if (parentInfo.index === -1) {
          for (let index in tree.subMenu) {
            parentInfo = this.findParent(id, tree.subMenu[index])
            if (parentInfo.index !== -1) {
              break
            }
          }
        } else {
          parentInfo.subMenu = tree.subMenu
        }
      }
      return parentInfo
    },
    checkPermitTree(checkedNodes, checkedKeys) {
      if (checkedKeys.checkedKeys.indexOf(checkedNodes.id) === -1) {
        this.currentSelectPermitId = ''
      } else {
        this.currentSelectPermitId = checkedNodes.id
      }
    },
    checkPermitTreeByName() {
      const node = this.findNode(this.queryCondition.permitName, this.permitTree[0].subMenu)
      if (node) {
        this.currentSelectPermitId = node.id
      }
    },
    findNode(name, treeRoot) {
      for (let node in treeRoot) {
        if (treeRoot[node].name.indexOf(name) !== -1) {
          return treeRoot[node]
        }
      }
      if (treeRoot.subMenu) {
        return this.findNode(name, treeRoot.subMenu)
      }
    },
    setCurrent(row) {
      this.$refs.singleTable.setCurrentRow(row)
    },
    handleCurrentRowChange(val) {
      this.currentRow = val
    },
    addPermit(permit) {
      const body = {
        clientType: this.queryCondition.clientType,
        ...permit
      }
      const _this = this
      this.fetch(
        this.apiName.addPermit,
        null,
        body,
        () => {
          _this.$message({
            showClose: true,
            message: '新增菜单成功',
            type: 'success',
            duration: 2000
          })
          _this.queryAllPermitList()
        },
        responseData => {
          _this.$alert('请求错误：' + responseData.data.message)
        }
      )
    },
    modifyPermit(permit) {
      const _this = this
      this.fetch(
        this.apiName.modifyPermit,
        null,
        permit,
        () => {
          _this.$message({
            showClose: true,
            message: '修改菜单成功',
            type: 'success',
            duration: 2000
          })
          _this.queryAllPermitList()
        },
        responseData => {
          _this.$alert('请求错误：' + responseData.data.message)
        }
      )
    },
    deletePermit(permit) {
      const _this = this
      this.fetch(
        this.apiName.deletePermit,
        null,
        permit,
        () => {
          _this.$message({
            showClose: true,
            message: '删除菜单成功',
            type: 'success',
            duration: 2000
          })
          _this.queryAllPermitList()
        })
    },
    queryAllPermitList() {
      const _this = this
      this.permitTree[0].subMenu = []
      this.fetch(this.apiName.queryAllPermitList, null, null, responseData => {
        const permitTrees = responseData.data || []
        permitTrees.forEach(tree => {
          if (tree.clientType === _this.queryCondition.clientType) {
            _this.permitTree[0].subMenu = tree.subMenu || []
          }
          _this.disableAllCheckBox(_this.permitTree[0].subMenu)
        })
        _this.isAddMode = false
        _this.isEditMode = false
      })
    },
    // 使checkbox禁选
    disableAllCheckBox(data) {
      data = data || []
      data.forEach(item => {
        item.disabled = true
        if (item.subList) {
          this.disableAllCheckBox(item.subList)
        }
      })
    },
    // 使checkbox可选
    enableAllCheckBox(data) {
      data = data || []
      data.forEach(item => {
        item.disabled = false
        if (item.subList) {
          this.enableAllCheckBox(item.subList)
        }
      })
    }
  }
}
</script>

<style scoped>
</style>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 15px;
  padding-right: 8px;
}

.custom-tree-node-container {
  flex: 1 1 auto;
  justify-content: flex-start;
}

.current-row {
  background-color: #c9e5f5 !important;
}

.role-container .el-collapse {
  overflow-x: hidden !important;
}

.role-container .el-collapse .el-collapse-item .el-collapse-item__header {
  height: 30px;
  line-height: 30px;
}

.role-container .el-collapse .el-collapse-item .el-collapse-item__header i {
  line-height: 30px;
}

.role-container .el-collapse .el-collapse-item .el-collapse-item__content {
  padding-bottom: 5px;
}

.role-container
  .el-collapse
  .el-collapse-item
  .el-collapse-item__content
  .el-tree-node__content {
  height: 20px;
  line-height: 20px;
}

.roleDialog .el-select .el-input {
  width: 200px;
}

.roleDialog .input-with-select .el-input-group__prepend {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  padding: 0;
}

.roleDialog .el-form-item__content .el-input {
  max-width: 85%;
}

.roleDialog .el-input-group__prepend .el-select {
  margin: -10px 0px;
}

/* .roleDialog .el-form-item__content .el-input .el-input__inner{
      margin-left: 10px;
    } */
.roleDialog .el-form-item__content .el-form-item__error {
  padding-top: 4px !important;
  margin-left: 141px;
}

.role-container .el-radio__label {
  padding-left: 0px;
}
</style>
